package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.CheckItemDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckItem;
import com.itheima.service.CheckItemService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;


/*
类简介：

功能：

时间：2020/3/28

*/
@Service(interfaceClass = CheckItemService.class)
public class CheckItemServiceImpl implements CheckItemService {

    @Autowired
    CheckItemDao checkItemDao;

    //新增检查项
    @Override
    public void add(CheckItem checkItem) {
        if (checkItemDao.ifExit(checkItem) > 0){
            throw new RuntimeException("已经存在重复项");
        }else {
            if(checkItemDao.add(checkItem) == 0){
                throw new RuntimeException("数据库请联系管理员");
            }
        }
    }

    //查询页面
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage()<0?1:queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        Page<CheckItem> checkItems;
        if (queryPageBean.getQueryString() != null){
            checkItems = checkItemDao.findPage("%" + queryPageBean.getQueryString().trim() + "%");
            return new PageResult(checkItems.getTotal(),checkItems.getResult());
        }else {
            checkItems = checkItemDao.findPage("%%");
            return new PageResult(checkItems.getTotal(),checkItems.getResult());
        }
    }

    //根据id删除
    @Override
    public void delete(int id) {
        if(checkItemDao.ifConnection(id) > 0){
            throw new RuntimeException("存在关联项，不允许删除");
        }else {
            int delete = checkItemDao.delete(id);
            if(delete == 0){
                throw new RuntimeException("数据库异常请联系管理员");
            }
        }

    }

    //根据id查询
    @Override
    public CheckItem findById(int id) {
        CheckItem checkItem = checkItemDao.findById(id);
        if (checkItem == null){
            throw new RuntimeException("数据库繁忙，稍后重试");
        }
        return checkItem;
    }

    //更新
    @Override
    public void upfata(CheckItem checkItem) {

        if(checkItemDao.updata(checkItem) == 0) {
            throw new RuntimeException("数据库异常请联系管理员");
        }
    }

    @Override
    public List<CheckItem> findAll() {
        List<CheckItem> checkItems = checkItemDao.findAll();
        if (checkItems == null){
            throw new RuntimeException("加载数据库错误，请联系管理员");
        }
        return checkItems;
    }
}
